package com.gljx.web.controller;


import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.util.*;
import com.gljx.web.Entity.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gljx.constant.ActivitiKey;
import com.gljx.web.dao.TimingChargeMapper;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.MessageService;
import com.gljx.web.service.TimingChargeEntryService;
import com.gljx.web.service.TimingChargeService;


@Controller
@RequestMapping("/")
public class timingChargeController {

	//自动注入
		@Autowired
		private TimingChargeService timingChargeService;

		@Autowired
		private TimingChargeEntryService timingChargeEntryService;

		@Autowired
		private CustomLogService customLogService;

		@Autowired
		private DepartmentService departmentService;

		//自动注入
		@Autowired
		private StudentController studentController;
		@Autowired
		private TimingChargeMapper timingChargeMapper;
		@Autowired
		private MessageService messageService;

//-----------------------------------分页与按条件查询计时收费单据-----------------------------------
	//@RequiresPermissions("/queryTimingCharge")
	@RequestMapping("/queryTimingCharge/look.action")
	public String queryTimingCharge(HttpServletRequest request,String type){
		PageBean<TrainCharge> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间
		String endTime = sdf.format(new Date());
		//获取前三天
		String beginTime = TimeFormat.getThreeDay();
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
			//获取当前分页的值
			List<TrainCharge> trainCharges = pb.getBeanList();
			for (TrainCharge trainCharge : trainCharges) {
				//获取子类信息
				List<TimingChargeEntry> timingChargeEntrys = timingChargeEntryService.queryTimingChargeEntry(trainCharge.getFid(), "", "", "");

				//获取科目对应的系统参数数据与计时时长乘积赋值给应收金额
				for(int j=0;j<timingChargeEntrys.size();j++) {
					if(timingChargeEntrys.get(j).getCfsubject()==null){
						break;
					}
					int	subjectNumber = timingChargeEntrys.get(j).getCfsubject();//科目数字
					String timingBeginTime = timingChargeEntrys.get(j).getCfbegintime();//计时开始时间
					String timingEndTime = timingChargeEntrys.get(j).getCfendtime();//计时结束时间
					String paramName = null;//系统参数名称
					timingBeginTime=timingBeginTime.replace("-","");
					timingBeginTime=timingBeginTime.replace(":","");
					timingBeginTime=timingBeginTime.replace(" ","");
					timingEndTime=timingEndTime.replace("-","");
					timingEndTime=timingEndTime.replace(":","");
					timingEndTime=timingEndTime.replace(" ","");

					if((timingBeginTime!=null&&!timingBeginTime.equals(""))&&
							(timingBeginTime!=null&&!timingBeginTime.equals(""))
							) {
						//训练时间
						long from = simpleFormat.parse(timingBeginTime).getTime();
						long to = simpleFormat.parse(timingEndTime).getTime();
						int timingHour = (int) ((to - from)/(1000 * 60 * 60));

						int timingMinute = Integer.parseInt(timingEndTime.substring(10, 12)) - Integer.parseInt(timingBeginTime.substring(10, 12));
						if(timingMinute>0) {
							timingHour = timingHour+1;
						}
						BigDecimal bigTimingHour = new BigDecimal(Integer.toString(timingHour));
						if(subjectNumber == 2) {
							paramName = "计时预约(科目二)/小时";
							TrainCharge paramList = timingChargeService.selectSystemParamByName(paramName);
							timingChargeEntrys.get(j).setCfysje(bigTimingHour.multiply(paramList.getParamNumber()));
						}else if(subjectNumber == 3){
							paramName = "计时预约(科目三)/小时";
							TrainCharge paramList = timingChargeService.selectSystemParamByName(paramName);
							timingChargeEntrys.get(j).setCfysje(bigTimingHour.multiply(paramList.getParamNumber()));
						}

					}

				}


				//放入集合
				trainCharge.setTimingChargeEntrys(timingChargeEntrys);
			}

			/*timingChargeService.selectSystemParamByName(paramId);*/

			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("department", department);
			request.setAttribute("trainCharges", trainCharges);
			request.setAttribute("pb", pb);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("flag", type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/backHome/financialManagement/timingCharge/timingChargeList";
	}





	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类
	 * @throws Exception
	 */

	public PageBean<TrainCharge> getPageBean(HttpServletRequest request,String companyId,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){
			offset=0;
		}else{
			offset=Integer.parseInt(request.getParameter("pager.offset"));
		}
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name zdrName,us.name shName,t.cfbillstate");
		psql.append(" from ct_ds_timingcharge t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid left join ct_ds_admin a on t.cfficompanyid =a.fid where t.fcontrolunitid = '"+companyId+"'");
		psql.append(" and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		psql.append(" order by t.FCREATETIME desc");
		int psize=10; //每页显示数
		int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= timingChargeService.selectPage(pindex, psql.toString(), psize);
		PageBean<TrainCharge> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<TrainCharge>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}



	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类
	 * @throws Exception
	 */
	public PageBean<TrainCharge> getPageBean2(HttpServletRequest request,String companyId,
			String studentName,String cfidcardno,String cftjr,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){
			offset=0;
		}else{
			offset=Integer.parseInt(request.getParameter("pager.offset"));
		}
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,t.fbizdate,t.zdrName,t.shName,t.cfbillstate from（");
		psql.append("select distinct t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name zdrName,us.name shName,t.cfbillstate ");
		psql.append(" from ct_ds_timingcharge t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid ");
		psql.append(" left join ct_ds_TimingChargeEntry tr on t.fid = tr.fparentid left join ct_ds_student s on tr.cfstudentid = s.fid left join ct_ds_admin a on t.cfficompanyid =a.fid ");
		psql.append(" where t.FCONTROLUNITID= '"+companyId+"' ");
		//psql.append(" and s.TIMINGCHARGE = 1");
		if("".equals(studentName)){

		}else{
			psql.append(" and s.fname_l2 like '%"+studentName+"%'");
		}
		if("".equals(cfidcardno)){

		}else{
			psql.append(" and tr.cfidcardno like '%"+cfidcardno+"%'");
		}
		if("".equals(cftjr)){

		}else{
			psql.append(" and tr.cftjr like '%"+cftjr+"%'");
		}
		if(!"".equals(beginTime) && !"".equals(endTime)){
			psql.append("  and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD') ");
		}else if ("".equals(beginTime) && !"".equals(endTime)){
			psql.append("  and t.fbizdate <= to_date('"+endTime+"','YYYY/MM/DD') ");
		}else if (!"".equals(beginTime) && "".equals(endTime)){
			psql.append("  and t.fbizdate >= to_date('"+beginTime+"','YYYY/MM/DD') ");
		}
		psql.append("）t order by fbizdate desc");
		int psize=10; //每页显示数
		int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= timingChargeService.selectPage(pindex, psql.toString(), psize);
		PageBean<TrainCharge> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<TrainCharge>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}





	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=timingChargeService.selectPageCount(psql);
		return paramMap;
	}







	/**
	 * 根据条件查询
	 * @param request
	 * @param studentName 学生名
	 * @param cfidcardno 身份证号
	 * @param cftjr 推荐人
	 * @param beginTime 开始时间
	 * @param endTime 结束时间
	 * @return
	 */
	@RequestMapping("/queryTimingChargeByinfo")
	public String queryTrainChargeByinfo(HttpServletRequest request,
			String studentName,String cfidcardno,String cftjr,String beginTime,String endTime){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		PageBean<TrainCharge> pb = new PageBean<>();
		try {
			//查询分页数据
			pb = getPageBean2(request,user.getFcompanyid(),studentName,cfidcardno,cftjr,beginTime,endTime);
			//获取数据
			List<TrainCharge> trainCharges = pb.getBeanList();
			for (TrainCharge trainCharge : trainCharges) {
				//获取子类信息
				List<TimingChargeEntry> timingChargeEntrys = timingChargeEntryService.queryTimingChargeEntry(trainCharge.getFid(), studentName, cfidcardno, cftjr);

				//获取科目对应的系统参数数据与计时时长乘积赋值给应收金额
				for(int j=0;j<timingChargeEntrys.size();j++) {
					int	subjectNumber = timingChargeEntrys.get(j).getCfsubject();//科目数字
					String timingBeginTime = timingChargeEntrys.get(j).getCfbegintime();//计时开始时间
					String timingEndTime = timingChargeEntrys.get(j).getCfendtime();//计时结束时间
					String paramName = null;//系统参数名称
					timingBeginTime=timingBeginTime.replace("-","");
					timingBeginTime=timingBeginTime.replace(":","");
					timingBeginTime=timingBeginTime.replace(" ","");
					timingEndTime=timingEndTime.replace("-","");
					timingEndTime=timingEndTime.replace(":","");
					timingEndTime=timingEndTime.replace(" ","");

					if((timingBeginTime!=null&&!timingBeginTime.equals(""))&&
							(timingBeginTime!=null&&!timingBeginTime.equals(""))
							) {
						//训练时间
						long from = simpleFormat.parse(timingBeginTime).getTime();
						long to = simpleFormat.parse(timingEndTime).getTime();
						int timingHour = (int) ((to - from)/(1000 * 60 * 60));

						int timingMinute = Integer.parseInt(timingEndTime.substring(10,12))-Integer.parseInt(timingBeginTime.substring(10,12));
						if(timingMinute>0) {
							timingHour = timingHour+1;
						}
						BigDecimal bigTimingHour = new BigDecimal(Integer.toString(timingHour));
						if(subjectNumber == 2) {
							paramName = "计时预约(科目二)/小时";
							TrainCharge paramList = timingChargeService.selectSystemParamByName(paramName);
							timingChargeEntrys.get(j).setCfysje(bigTimingHour.multiply(paramList.getParamNumber()));
						}else if(subjectNumber == 3){
							paramName = "计时预约(科目三)/小时";
							TrainCharge paramList = timingChargeService.selectSystemParamByName(paramName);
							timingChargeEntrys.get(j).setCfysje(bigTimingHour.multiply(paramList.getParamNumber()));
						}

					}

				}

				//放入集合
				trainCharge.setTimingChargeEntrys(timingChargeEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("department", department);
			request.setAttribute("trainCharges", trainCharges);
			request.setAttribute("studentName", studentName);
			request.setAttribute("cfidcardno", cfidcardno);
			request.setAttribute("cftjr", cftjr);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("pb", pb);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/backHome/financialManagement/timingCharge/timingChargeList";
	}

	//------------------------------------添加单据-----------------------------
	/**
	 * 添加计时收费
	 * @param request
	 * @param timingCharge 属性自动封装
	 * @return
	 */
	//@RequiresPermissions("/addTimingCharge")
	@RequestMapping("/addTimingCharge")
	public String addTrainCharge(HttpServletRequest request,TrainCharge timingCharge){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//利用UUID生成fid
		timingCharge.setFid(GetFid.UUIDIntoFid());
		//控制单元id
		timingCharge.setFcontrolunitid(user.getFcompanyid());
		//创建人id
		timingCharge.setFcreatorid(user.getFid());
		//公司id
		timingCharge.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String createTime = TimeFormat.timeFormat(new Date());
		//当前时间
		timingCharge.setFcreatetime(createTime);
		//操作人id
		timingCharge.setFhandlerid(user.getFid());
		//状态
		timingCharge.setCfbillstate((long)3);
		//获取子类信息
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//学员编码
		String[] cfstudentno = request.getParameterValues("cfstudentno");
		//学员id
		String[] cfstudentid = request.getParameterValues("cfstudentid");
		//学生姓名
		String[] cfstudentname = request.getParameterValues("studentName");
		//学员性别
		String[] cfsex = request.getParameterValues("cfsex");
		//学员身份证号
		String[] cfidcardno = request.getParameterValues("cfidcardno");
		//学员身份证地址
		String[] cfidcardaddress = request.getParameterValues("cfidcardaddress");
		//推荐人
		String[] cftjr = request.getParameterValues("cftjr");
		//班级
		String[] cfclazz = request.getParameterValues("cfclazz");
		//班级金额
		String[] cfclazzamount = request.getParameterValues("cfclazzamount");
		//已收
		String[] cfyishou = request.getParameterValues("cfyishou");
		//应收
		String[] cfysje = request.getParameterValues("cfysje");
		//规费
		String[] cfguifei = request.getParameterValues("cfguifei");
		//培训费
		String[] cfpxf = request.getParameterValues("cfpxf");
		//现金
		String[] cfcash = request.getParameterValues("cfcash");
		//刷卡
		String[] cfcard = request.getParameterValues("cfcard");
		//挂账
		String[] cfguazhang = request.getParameterValues("cfguazhang");
		//训练科目
		String[] trainObject = request.getParameterValues("trainObject");
		//训练开始时间
		String[] timingStartTime = request.getParameterValues("timingStartTime");
		//训练结束时间
		String[] timingEndTime = request.getParameterValues("timingEndTime");
		//银行转账
		String[] cfyhzz = request.getParameterValues("cfyhzz");
		//实收金额
		String[] cfshje = request.getParameterValues("cfshje");
		//优惠金额
		String[] cfyhje = request.getParameterValues("cfyhje");
		//优惠劵
		String[] cfyhj = request.getParameterValues("cfyhj");
		//欠费金额
		String[] cfqfje = request.getParameterValues("cfqfje");
		//备注
		String[] cfremark = request.getParameterValues("cfremark");
		//训练科目
		String[] cfsubject = request.getParameterValues("cfsubject");
		//教练姓名
		String[] cfcoachname = request.getParameterValues("cfcoachname");
		//计时开始时间
		String[] cfbegintime = request.getParameterValues("cfbegintime");
		//计时结束时间
		String[] cfendtime = request.getParameterValues("cfendtime");

		//添加
		timingChargeService.addTimingCharge(timingCharge,fseq,cfstudentno, cfstudentid, cfsex, cfidcardno,cfidcardaddress, cftjr, cfclazz, cfclazzamount,
				cfyishou, cfysje, cfguifei, cfpxf, cfcash, cfcard, cfguazhang,trainObject,timingStartTime,timingEndTime, cfyhzz, cfshje, cfyhje, cfyhj, cfqfje, cfremark,
				cfsubject,cfcoachname,cfbegintime,cfendtime,cfstudentname);

		//添加日志
		List<CustomLog> customLogs = new ArrayList<>();
		for (int i = 0; i < cfstudentid.length; i++) {
			CustomLog customLog = new CustomLog();
			customLog.setFid(GetFid.UUIDIntoFid());
			customLog.setFcreatetime(createTime);
			customLog.setFcreatorid(user.getFid());
			customLog.setCfstudentid(cfstudentid[i]);
			customLog.setFnameL2("计时收费");
			customLog.setFdescriptionL2("新增学员:" + cfstudentno[i] + cfstudentname[i] + "缴费金额：" + cfshje[i] + "单据编号:" + timingCharge.getFnumber());
			//控制单元
			customLog.setFcontrolunitid(user.getFcompanyid());
			customLogs.add(customLog);
		}
		customLogService.insertCustomLog(customLogs);
		//customLogService.addLog("计时收费", "对计时收费进行添加操作", null, user.getFid());
		//重定向到添加页面
		return "redirect:/DrivingSys/insertTimingCharge?type=3";
	}



	/**
	 * 跳转到添加页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/insertTimingCharge")
	public String insertTrainCharge(HttpServletRequest request,String type,Student student){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编码
        /*String fnumber = customLogService.selectFunmber("ct_ds_timingcharge",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("YW");
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String endTime = sdf.format(new Date());
		String beginTime = TimeFormat.getMonth();
		student.setCfbegintime(beginTime);
		student.setCfendtime(endTime);
		try {
			//Map map = studentController.getPageBean3(request, "", "", "1", beginTime, endTime);//调用学员方法
			List<Student> stu = studentController.selectTimingStudent(student,request);//调用学员方法
			request.setAttribute("flag", 1);				//是否为新增记录
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			//request.setAttribute("pb", map.get("pb"));
			request.setAttribute("students", stu);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//把数据传到页面
		request.setAttribute("name", user.getName());
		request.setAttribute("date", endTime);
		request.setAttribute("fnumber", number);
		request.setAttribute("department", department);
		request.setAttribute("type", type);
		return "/backHome/financialManagement/timingCharge/editTimingCharge";
	}



	/**
	 * 根据fid查询
	 * @param request
	 * @param fid
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/selectTimingChargeByFid")
	public String selectTimingChargeByFid(HttpServletRequest request,String fid,Student student) throws ParseException{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取父类信息
		TrainCharge trainCharge = timingChargeService.queryByTrainChargeFid(fid);
		//查询子类信息
		List<TimingChargeEntry> timingChargeEntrys = timingChargeEntryService.queryTrainChargeEntrysByFparentId(fid);

		//获取科目对应的系统参数数据与计时时长乘积赋值给应收金额
		for(int j=0;j<timingChargeEntrys.size();j++) {
			if(timingChargeEntrys.get(j).getCfsubject()!=null) {
				int	subjectNumber = timingChargeEntrys.get(j).getCfsubject();//科目数字
				String timingBeginTime = timingChargeEntrys.get(j).getCfbegintime();//计时开始时间
				String timingEndTime = timingChargeEntrys.get(j).getCfendtime();//计时结束时间
				String paramName = null;//系统参数名称
				timingBeginTime=timingBeginTime.replace("-","");
				timingBeginTime=timingBeginTime.replace(":","");
				timingBeginTime=timingBeginTime.replace(" ","");
				timingEndTime=timingEndTime.replace("-","");
				timingEndTime=timingEndTime.replace(":","");
				timingEndTime=timingEndTime.replace(" ","");

				if((timingBeginTime!=null&&!timingBeginTime.equals(""))&&
						(timingBeginTime!=null&&!timingBeginTime.equals(""))
						) {
					//训练时间
					long from = simpleFormat.parse(timingBeginTime).getTime();
					long to = simpleFormat.parse(timingEndTime).getTime();
					int timingHour = (int) ((to - from)/(1000 * 60 * 60));

					int timingMinute = Integer.parseInt(timingEndTime.substring(10,12))-Integer.parseInt(timingBeginTime.substring(10,12));
					if(timingMinute>0) {
						timingHour = timingHour+1;
					}
					BigDecimal bigTimingHour = new BigDecimal(Integer.toString(timingHour));
					if(subjectNumber == 2) {
						paramName = "计时预约(科目二)/小时";
						TrainCharge paramList = timingChargeService.selectSystemParamByName(paramName);
						timingChargeEntrys.get(j).setCfysje(bigTimingHour.multiply(paramList.getParamNumber()));
					}else if(subjectNumber == 3){
						paramName = "计时预约(科目三)/小时";
						TrainCharge paramList = timingChargeService.selectSystemParamByName(paramName);
						timingChargeEntrys.get(j).setCfysje(bigTimingHour.multiply(paramList.getParamNumber()));
					}

				}
			}
		}


		if(trainCharge.getCfbillstate() == 5){
			request.setAttribute("sh", "5");
		}else{
			//获取当前时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String endTime = sdf.format(new Date());
			String beginTime = TimeFormat.getMonth();
			try {
				//Map map = studentController.getPageBean3(request, "", "", "1", beginTime, endTime);//调用学员方法
				List<Student> stu = studentController.selectTimingStudent(student,request);//调用学员方法
				request.setAttribute("flag", 1);				//是否为新增记录
				request.setAttribute("beginTime", beginTime);
				request.setAttribute("endTime", endTime);
				//request.setAttribute("pb", map.get("pb"));
				request.setAttribute("students", stu);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//把数据传到页面
		request.setAttribute("timingChargeEntries", timingChargeEntrys);
		request.setAttribute("department", department);
		request.setAttribute("trainCharge", trainCharge);
		request.setAttribute("auditState",selectProcessState(trainCharge.getFnumber()) );
		return "/backHome/financialManagement/timingCharge/editTimingCharge";
	}




	/**
	 * 根据fid删除
	 * @param request
	 * @param deleteId 多个fid
	 * @param fid 单个fid
	 * @return
	 */
	//@RequiresPermissions("/deleteTimingChargeByFid")
	@RequestMapping("/deleteTimingChargeByFid")
	public String deleteTranChargeByFid(HttpServletRequest request,String deleteId[],String fid,String[] fnumber,String fnumber2){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//添加日志
		String time = TimeFormat.timeFormat(new Date());
		List<CustomLog> customLogs = new ArrayList<>();
		if (fid == null) {
			for (int i = 0; i < deleteId.length; i++) {
				List<TimingChargeEntry> trainChargeEntries = timingChargeEntryService.queryTrainChargeEntrysByFparentId(deleteId[i]);
				for (TimingChargeEntry trainChargeEntrie : trainChargeEntries) {
					CustomLog customLog2 = new CustomLog();
					customLog2.setFid(GetFid.UUIDIntoFid());
					customLog2.setFcreatetime(time);
					customLog2.setFcreatorid(user.getFid());
					customLog2.setCfstudentid(trainChargeEntrie.getCfstudentid());
					customLog2.setFnameL2("计时收费");
					System.out.println(trainChargeEntrie.getFnumber());
					customLog2.setFdescriptionL2("删除学员:" + trainChargeEntrie.getCfstudentno() + trainChargeEntrie.getStudentName() + "单据编号:" + fnumber[i]);
					//控制单元
					customLog2.setFcontrolunitid(user.getFcompanyid());
					customLogs.add(customLog2);
				}
				//删除流程
			}
		} else {
			List<TimingChargeEntry> trainChargeEntries = timingChargeEntryService.queryTrainChargeEntrysByFparentId(fid);
			//删除流程
			for (TimingChargeEntry trainChargeEntrie : trainChargeEntries) {
				CustomLog customLog = new CustomLog();
				customLog.setFid(GetFid.UUIDIntoFid());
				customLog.setFcreatetime(time);
				customLog.setFcreatorid(user.getFid());
				customLog.setCfstudentid(trainChargeEntrie.getCfstudentid());
				customLog.setFnameL2("计时收费");
				customLog.setFdescriptionL2("删除学员:" + trainChargeEntrie.getCfstudentno() + trainChargeEntrie.getStudentName() + "单据编号:" + trainChargeEntrie.getFnumber());
				//控制单元
				customLog.setFcontrolunitid(user.getFcompanyid());
				customLogs.add(customLog);
			}
		}
		timingChargeEntryService.deleteTranChargeByFid(deleteId, fid,fnumber,fnumber2);
		customLogService.insertCustomLog(customLogs);
		//customLogService.addLog("财务管理", TimeFormat.timeFormat(new Date())+"对计时收费进行删除操作", null, user.getFid());
		//重定向到查询方法
		return "redirect:/DrivingSys/queryTimingCharge/look.action";
	}




	/**
	 * 修改计时收费
	 * @param request
	 * @param trainCharge
	 * @return
	 */
	//@RequiresPermissions("/modifyTimingCharge")
	@RequestMapping("/modifyTimingCharge")
	public String modifyTrainCharge(HttpServletRequest request,TrainCharge trainCharge){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		trainCharge.setFcontrolunitid(user.getFcompanyid());
		//创建人id
		trainCharge.setFlastupdateuserid(user.getFid());
		//公司id
		trainCharge.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String updateTime = TimeFormat.timeFormat(new Date());
		//当前时间
		trainCharge.setFlastupdatetime(updateTime);
		//操作人id
		trainCharge.setFhandlerid(user.getFid());
		//获取子类信息
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//学员编码
		String[] cfstudentno = request.getParameterValues("cfstudentno");
		//学员姓名
		String[] cfstudentid = request.getParameterValues("cfstudentid");
		//学员性别
		String[] cfsex = request.getParameterValues("cfsex");
		//学员身份证号
		String[] cfidcardno = request.getParameterValues("cfidcardno");
		//学员身份证地址
		String[] cfidcardaddress = request.getParameterValues("cfidcardaddress");
		//推荐人
		String[] cftjr = request.getParameterValues("cftjr");
		//班级
		String[] cfclazz = request.getParameterValues("cfclazz");
		//班级金额
		String[] cfclazzamount = request.getParameterValues("cfclazzamount");
		//已收
		String[] cfyishou = request.getParameterValues("cfyishou");
		//应收
		String[] cfysje = request.getParameterValues("cfysje");
		//规费
		String[] cfguifei = request.getParameterValues("cfguifei");
		//培训费
		String[] cfpxf = request.getParameterValues("cfpxf");
		//现金
		String[] cfcash = request.getParameterValues("cfcash");
		//刷卡
		String[] cfcard = request.getParameterValues("cfcard");
		//挂账
		String[] cfguazhang = request.getParameterValues("cfguazhang");
		//银行转账
		String[] cfyhzz = request.getParameterValues("cfyhzz");
		//实收金额
		String[] cfshje = request.getParameterValues("cfshje");
		//优惠金额
		String[] cfyhje = request.getParameterValues("cfyhje");
		//优惠劵
		String[] cfyhj = request.getParameterValues("cfyhj");
		//欠费金额
		String[] cfqfje = request.getParameterValues("cfqfje");
		//备注
		String[] cfremark = request.getParameterValues("cfremark");
		//训练科目
		String[] cfsubject = request.getParameterValues("cfsubject");
		//教练姓名
		String[] cfcoachname = request.getParameterValues("cfcoachname");
		//计时开始时间
		String[] cfbegintime = request.getParameterValues("cfbegintime");
		//计时结束时间
		String[] cfendtime = request.getParameterValues("cfendtime");
		//学生姓名
		String[] cfstudentname = request.getParameterValues("studentName");
		//添加
		timingChargeService.modifyTimingCharge(trainCharge, fseq, cfstudentno, cfstudentid, cfsex, cfidcardno,cfidcardaddress, cftjr, cfclazz, cfclazzamount,
				cfyishou, cfysje, cfguifei, cfpxf, cfcash, cfcard, cfguazhang, cfyhzz, cfshje, cfyhje, cfyhj, cfqfje, cfremark,cfsubject,cfcoachname,cfbegintime,cfendtime,cfstudentname);

		//添加日志
		List<CustomLog> customLogs = new ArrayList<>();
		for (int i = 0; i < cfstudentid.length; i++) {
			CustomLog customLog = new CustomLog();
			customLog.setFid(GetFid.UUIDIntoFid());
			customLog.setFcreatetime(updateTime);
			customLog.setFcreatorid(user.getFid());
			customLog.setCfstudentid(cfstudentid[i]);
			customLog.setFnameL2("计时收费");
			customLog.setFdescriptionL2("修改学员:" + cfstudentno[i] + cfstudentname[i] + "缴费金额：" + cfshje[i] + "单据编号:" + trainCharge.getFnumber());
			//控制单元
			customLog.setFcontrolunitid(user.getFcompanyid());
			customLogs.add(customLog);
		}
		customLogService.insertCustomLog(customLogs);
		//重定向到查询方法
		return "redirect:/DrivingSys/queryTimingCharge/look.action?type=4";
	}



	/**
	 * 审核计时收费
	 * @param request
	 * @param fid
	 * @return
	 */
	//@RequiresPermissions("/auditTimingCharge")
	@RequestMapping("/auditTimingCharge")
	@ResponseBody
	public String auditTrainCharge(HttpServletRequest request,String fid,String type){
		TrainCharge trainCharge = new TrainCharge();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		if("1".equals(type)){
			//审核人id
			trainCharge.setFauditorid(user.getFid());
			//状态
			trainCharge.setCfbillstate(5L);
			//fid
			trainCharge.setFid(fid);
			List<TimingChargeEntry> timingChargeEntries = timingChargeEntryService.queryTrainChargeEntrysByFparentId(fid);
			timingChargeService.auditTrainCharge(timingChargeEntries,trainCharge);
		}else{
			//审核人id
			trainCharge.setFauditorid(user.getFid());
			//状态
			trainCharge.setCfbillstate(4L);
			//fid
			trainCharge.setFid(fid);
			//修改
			timingChargeService.updateTimingCharge(trainCharge);
		}
		return "1";
	}


	/*//BigDecimal乘法运算
	public  double mul(double v1,double v2){
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
		} */


	//日期格式化
	SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyyMMddHHmmss");



    //-----------------------------------------------计时收费流程-----------------------------------------------

    ActitiviUtil activitiUtil = new ActitiviUtil();

    /**
     * 提交后开始流程并推进至下一节点
     * @param request
     * @param fnumber 单据编号
     */
    @RequestMapping(value = "/startProcessTimingCharge")
    @ResponseBody
    public void startProcess(HttpServletRequest request,String fnumber,String fid,String auditState,
							 @RequestParam(value = "studentName[]", defaultValue = "") String[] studentName,
							 @RequestParam(value = "studentId[]", defaultValue = "") String[] studentId,
							 @RequestParam(value = "cfstudentno[]", defaultValue = "") String[] cfstudentno) {
    	String flowKey = "Driving_Sys_timingCharge"; //流程的id

    	//启动流程并设置流程变量
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put(ActivitiKey.PUBLIC_PROCESS, fnumber);

    	if(auditState.equals("noProcess")||auditState.equals("processEnd")){
	    	String piID = activitiUtil.creatFlow(flowKey, map);
	    	System.out.println("单据编号:"+fnumber);

	    	//4.如果你有“提交”这个流程，那么你还要补上一步，将流程推进到提交的下一步
	        Message message = activitiUtil.completeFlowByPiID(piID);
    	}


    	//--------------判断有历史流程添加此方法------------
        System.out.println("auditState:"+auditState);
        if(auditState.equals("processing")){
	        /*审核过程中的单据被打回调此方法*/
	        Message message2 = activitiUtil.complteFlowByVariable(
	                ActivitiKey.PUBLIC_PROCESS,  //指定要启动的流程定义
	                fnumber                     //流程变量
	        );

        }


        //--------------判断有历史流程添加此方法------------
    	TrainCharge trainCharge = new TrainCharge();
    	//获取当前用户
    	User user = (User) request.getSession().getAttribute("user");
    	/*//获取当前时间
    	String updateTime = TimeFormat.timeFormat(new Date());

    	//修改时间
    	trainCharge.setFlastupdatetime(updateTime);
    	trainCharge.setFauditorid(user.getFid());*/
    	trainCharge.setFid(fid);
    	trainCharge.setCfbillstate(Long.valueOf("4"));

		//添加日志
		customLogService.addLog("计时收费", "对计时收费提交操作单据编号 " + fnumber, null, user.getFid());
    	timingChargeMapper.updateByPrimaryKeySelective(trainCharge);

    }


  //点击审核
    @RequestMapping(value = "/auditProcessTimingCharge")
    @ResponseBody
    public int auditProcess(HttpServletRequest request,String fnumber,String message,Integer state,String fid) {
    	Object returnMsg = activitiUtil.auditComplte(ActivitiKey.PUBLIC_PROCESS, fnumber, state, message);
    	int endOrNot = 0;	//判断流程状态（1.通过 2.通过且结束 3.当前用户不是经办人）
    	//System.out.println("通过原因:"+message);
    	TrainCharge trainCharge = new TrainCharge();
    	//获取当前用户
    	User user = (User) request.getSession().getAttribute("user");
    	//获取当前时间
    	String updateTime = TimeFormat.timeFormat(new Date());


    	if(activitiUtil.notAssign .equals(returnMsg))
        {
    		endOrNot = 3;
            System.out.println("当前用户不是要求的经办人,没有审核权限！");

        }
        else if(activitiUtil.FINISH.equals(returnMsg))
        {
        	trainCharge.setFlastupdatetime(updateTime);
        	trainCharge.setFauditorid(user.getFid());
        	trainCharge.setFid(fid);
        	trainCharge.setCfbillstate(Long.valueOf("5"));
        	timingChargeMapper.updateByPrimaryKeySelective(trainCharge);
            endOrNot = 2;
			//添加日志
			customLogService.addLog("计时收费", "对计时收费审核通过操作单据编号 " + fnumber, null, user.getFid());
            System.out.println("此流程成功推进，并且此流程已经结束");
        }
        else if(activitiUtil.SUCCESS.equals(returnMsg))
        {
        	/*trainCharge.setFlastupdatetime(updateTime);
        	trainCharge.setFauditorid(user.getFid());*/
        	trainCharge.setFid(fid);
        	if(state == 0){
        		trainCharge.setCfbillstate(Long.valueOf("3"));
				//添加日志
				customLogService.addLog("计时收费", "对计时收费审核不通过操作单据编号 " + fnumber, null, user.getFid());
        	}
        	timingChargeMapper.updateByPrimaryKeySelective(trainCharge);
            endOrNot = 1;
            System.out.println("此流程成功推进");
        }
        else if(activitiUtil.notTask.equals(returnMsg))
        {
        	endOrNot = 0;
            System.out.println("没有找到正在进行的相关流程");
        }
		return endOrNot;	//判断流程是否结束;

    }


  //3.反审核
    //@RequiresPermissions("/failAuditProcessTimingCharge")
    @RequestMapping(value = "/failAuditProcessTimingCharge")
    @ResponseBody
    public void failAuditProcess(HttpServletRequest request,String fnumber,String fid,String message,String auditState) {
		//获取当前用户
		User user = (User) request.getSession().getAttribute("user");
    	if(auditState.equals("processEnd")){//流程结束反审核
    		Message message2 = activitiUtil.getMessage(
                    ActivitiKey.PUBLIC_PROCESS,
                    fnumber                  //单据
            );

    	}else{		//流程中反审核
    		String result = activitiUtil.jumpActivti(
                    ActivitiKey.PUBLIC_PROCESS,
                    fnumber,                  //单据
                    message
            );
            if (activitiUtil.SUCCESS.equals(result)) {
				System.out.println("反审核成功");

			} else if (activitiUtil.notActiviti.equals(result)) {
				System.out.println("找不到流程节点");

			} else if (activitiUtil.notTask.equals(result)) {
				System.out.println("没有找到任务");
			}
    	}

    	TrainCharge trainCharge = new TrainCharge();
        /*//获取当前用户
    	User user = (User) request.getSession().getAttribute("user");
    	//获取当前时间
    	String updateTime = TimeFormat.timeFormat(new Date());

    	//修改时间
    	trainCharge.setFlastupdatetime(updateTime);
    	trainCharge.setFauditorid(user.getFid());*/
    	trainCharge.setCfbillstate(Long.valueOf("3"));
    	trainCharge.setFid(fid);
    	timingChargeMapper.updateByPrimaryKeySelective(trainCharge);
		//添加日志
		customLogService.addLog("计时收费", "对计时收费反审核操作单据编号 " + fnumber, null, user.getFid());
    }




    //判断流程状态
    public String selectProcessState(Object fnumber){
    	String result = activitiUtil.getTaskStateByUser(
                ActivitiKey.PUBLIC_PROCESS,
                fnumber                 //单据
        );
        if(activitiUtil.notTask.equals(result))
        {
            System.out.println("改单据没有对应流程");			//没有历史流程（从来没有过流程的“新单据”）
            return "noProcess";

        }else if(activitiUtil.FINISH.equals(result))
        {
            System.out.println("流程已结束");				//只有有历史流程
            return "processEnd";
        }//剩下两种是该任务进行中
        else if(activitiUtil.notAssign.equals(result))
        {
            System.out.println("经办人不匹配");				//正在进行的流程，但是经办人跟当前用户不匹配
            return "peopleNot";
        }else if(activitiUtil.ISPOWER.equals(result))
        {
            System.out.println("当前用户可以审核该单据");			/**正在进行的流程，且当前用户能够审核
             												* 如果是进入可提交的详情页面，这个标记表示
             												* 此流程进行中，即用户点击提交只需推进流程即可
             												*/
            return "processing";
        }else{
        	return "nothing";
        }
    }

	//----------------------------------------导出excel-------------------------------------------
	/**
	 * 导出Execl
	 *
	 * @param response
	 */
	@RequestMapping("/importTimingCharge")
	public void importTrainCharge(HttpServletResponse response, HttpServletRequest request,
								  String studentName, String cfidcardno, String cftjr, String beginTime, String endTime) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		List<Object> data = new ArrayList<>();
		//查询数据
		List<TimingChargeEntry> timingChargeEntrys = timingChargeEntryService.selectTimingChargeExcel(studentName, cfidcardno, cftjr, beginTime, endTime, user.getFcompanyid());
		for (TimingChargeEntry timingChargeEntry : timingChargeEntrys) {
			data.add(timingChargeEntry.getFnumber());//单据编号
			data.add(timingChargeEntry.getCompanyName());//驾校
			data.add(timingChargeEntry.getFbizdate());//业务日期
			data.add(timingChargeEntry.getShName());//审核人
			data.add(timingChargeEntry.getZdrName());//制单人名称
			if (timingChargeEntry.getCfbillstate() == 3) {
				data.add("保存");//单据状态
			} else if (timingChargeEntry.getCfbillstate() == 4) {
				data.add("提交");//单据状态
			} else if (timingChargeEntry.getCfbillstate() == 5) {
				data.add("审核");//单据状态
			} else {
				data.add(null);//单据状态
			}
			data.add(timingChargeEntry.getCfstudentno());//学员编码
			data.add(timingChargeEntry.getStudentName());//学员
			if (timingChargeEntry.getCfsex() == null) {
				data.add(null);//性别
			} else if (timingChargeEntry.getCfsex() == 2) {
				data.add("女");//性别
			} else {
				data.add("男");//性别
			}
			data.add(timingChargeEntry.getCfidcardno());//身份证号
			data.add(timingChargeEntry.getCfidcardaddress());//身份证地址
			data.add(timingChargeEntry.getCftjr());//推荐人
			if(timingChargeEntry.getCfsubject()==2){//训练科目
				data.add("科目二");
			}else if(timingChargeEntry.getCfsubject()==3){
				data.add("科目三");
			}
			data.add(timingChargeEntry.getCfcoachname());//教练名称
			data.add(timingChargeEntry.getCfbegintime());//训练开始时间
			data.add(timingChargeEntry.getCfendtime());//训练结束时间
			data.add(timingChargeEntry.getCfyishou());//已收
			data.add(timingChargeEntry.getCfysje());//应收金额
			data.add(timingChargeEntry.getCfcash());//现金
			data.add(timingChargeEntry.getCfcard());//刷卡
			data.add(timingChargeEntry.getCfshje());//实收金额
			data.add(timingChargeEntry.getCfyhje());//优惠金额
			data.add(timingChargeEntry.getCfqfje());//欠费金额
			data.add(timingChargeEntry.getCfguazhang());//挂账
			data.add(timingChargeEntry.getCfyhzz());//银行转账
			//data.add(timingChargeEntry.getCfdycs());//打印次数
			data.add(timingChargeEntry.getCfyhj());//优惠券
		}
		//头部数据
		String head[] = {"单据编码", "驾校", "业务日期", "审核人名称", "制单人名称", "单据状态", "学员编码", "学员", "性别", "身份证号", "身份证地址", "推荐人", "训练科目", "教练","练车开始时间","练车结束时间", "已收", "应收金额",
				"现金", "刷卡", "实收金额", "优惠金额", "欠费金额","挂账", "银行转账","优惠券"};
		//长度
		Integer length[] = {6500, 6000, 3000, 3000, 3000, 3000, 6200, 2600, 1500, 5000, 6500, 3000, 3000, 3000, 5500, 5500, 3000, 3000,3000, 3000, 3000, 3000, 3000,3000,3000, 3000};
		List<Object> data2=listForSum(data,head,16,head.length-16);

		try {
			//导出Excel
			CommonExport.importExcelSum(response, "计时收费" + TimeFormat.getNowTime2() + ".xls", "计时收费", data, head, length,data2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 *统计方法
	 * @param list1 完成遍历的集合
	 * @param head  表头
	 * @param num   求和的第一个字段的下标
	 * @param sum  需要增加多少个字段
	 * @return
	 */
	public List<Object> listForSum(List<Object> list1,String[] head,int num,int sum){

		Double money=0.0;

		List<Object>list=new ArrayList<>();
		DecimalFormat df = new DecimalFormat("#.00");
		list.add("合计：");
		for (int i = 0; i < num - 1; i++) {
			list.add(" ");
		}
		for(int i=0;i<sum;i++){

			for (int j = 0; j < list1.size() / head.length; j++) {
				if (list1.get(num + head.length*j)==null || "".equals(list1.get(num + head.length * j))) {
					money += 0.00;
				} else {
					money += Double.parseDouble(list1.get(num + head.length * j) + "");
				}
			}
			if(money==0.00||money==null){
				list.add("0.00");
			}else{
				if(".00".equals(df.format(money))){
					list.add("");
				}else{
					list.add(df.format(money));
				}
			}
			num++;
			money = 0.00;
		}
		return list;
	}

}
